package com.jintu.portal.service.datadriver.receiver;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.service.datadriver.repository.SourceDataMongoDao;
import com.jintu.portal.cache.RedisHelper;
import com.jintu.portal.service.datadriver.DataRequestHandler;
import com.jintu.portal.service.datadriver.pojo.MsgRespCode;
import com.jintu.portal.service.datadriver.pojo.RespInfo;
import com.jintu.portal.service.datadriver.pojo.Response;
import com.jintu.portal.service.datadriver.pojo.SysRespCode;
import com.jintu.portal.service.datadriver.pojo.entity.SourceData;
import com.jintu.portal.utils.CommonUtil;
import com.jintu.portal.utils.GZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * @author very
 */
@Slf4j
@RestController
@RequestMapping("/receive/carrierReceiver")
public class CarrierReceiver {

    private static final String QUERY_ZIP_REPORT = "QUERY_ZIP_REPORT";
    private static final String QUERY_ZIP_MOBILE = "QUERY_ZIP_MOBILE";
    private static final String REPORT_COLLECTION_NAME_SURFIX = "Report";

    @Resource(name = "dataRequestHandler")
    private DataRequestHandler dataRequestHandler;

    @Resource(name = "redisHelper")
    private RedisHelper redisHelper;

    @Resource(name = "sourceDataMongoDao")
    private SourceDataMongoDao sourceDataMongoDao;

    @Resource(name = "receiverCommonUtil")
    private ReceiverCommonUtil receiverCommonUtil;

    @RequestMapping(method = RequestMethod.POST)
    public JSONObject receive(@RequestBody Response response) {
        JSONObject ret = new JSONObject();
        ret.put("code", "0000");
        try {
            log.info("运营商数据爬去成功，原始返回数据为：{}", JSONObject.toJSONString(response));
            if (SysRespCode.QUERY_SUCCESS.getCode().equals(response.getRetCode())) {
                RespInfo respInfo = response.getRetInfo();
                String merchPrivateString = response.getMerchPrivate();
                if (StringUtils.isBlank(merchPrivateString)) {
                    log.error("用户merchPrivate为空，无法还原风控订单信息");
                } else {
                    JSONObject riskOrderInfo = JSONObject.parseObject(merchPrivateString);
                    String orderId = riskOrderInfo.getString("orderId");
                    if (respInfo != null && MsgRespCode.SEARCH.getCode().equals(respInfo.getCode())) {
                        String tradeNo = redisHelper.get(riskOrderInfo.getString("dataSourceCode") + "_" + orderId);
                        if (StringUtils.isBlank(tradeNo)) {
                            log.error("风控订单【{}】从数据库中获取tradeNo为空，运营商数据爬去失败", orderId);
                        } else {
                            log.info("开始获取运营商报告和原始数据信息");
                            queryCarrierData(riskOrderInfo, tradeNo, QUERY_ZIP_REPORT);
                            // 根据爬虫要去睡5s再起请求
                            Thread.sleep(5 * 1000);
                            queryCarrierData(riskOrderInfo, tradeNo, QUERY_ZIP_MOBILE);
                        }
                    }
                    receiverCommonUtil.changeFlagAndSendMq(riskOrderInfo, null);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ret;
    }

    private void queryCarrierData(JSONObject riskOrderInfo, String tradeNo, String optType) throws Exception {
        String idCard = riskOrderInfo.getString("idCard");
        String mobile = riskOrderInfo.getString("mobile");
        String realName = riskOrderInfo.getString("realName");
        String collectionName = "";
        if (QUERY_ZIP_REPORT.equals(optType)) {
            collectionName = riskOrderInfo.getString("dataSourceCode") + REPORT_COLLECTION_NAME_SURFIX;
        } else if (QUERY_ZIP_MOBILE.equals(optType)) {
            collectionName = riskOrderInfo.getString("dataSourceCode");
        }

        JSONObject req = new JSONObject();
        req.put("idCard", idCard);
        req.put("mobile", mobile);
        req.put("realName", realName);
        req.put("tradeNo", tradeNo);
        req.put("optType", optType);
        // 获取原始数据解析并存储
        String responseContent = dataRequestHandler.sendDataRequest(
                receiverCommonUtil.genDataRequestOrderId(riskOrderInfo.getString("orderId")),
                riskOrderInfo.getString("orderId"),
                riskOrderInfo.getString("dataSourceInterface"),
                req.toJSONString());
        Response response = JSONObject.parseObject(responseContent, Response.class);
        if (SysRespCode.QUERY_SUCCESS.getCode().equals(response.getRetCode())
                && MsgRespCode.SEARCH.getCode().equals(response.getRetInfo().getCode())) {
            String encodedData = (String) response.getRetInfo().getMessage();
            String srcData = GZipUtil.ungzipString(encodedData, "UTF-8");
            Document carrierData = new Document();
            carrierData.putAll(JSONObject.parseObject(srcData));
            SourceData carrier = new SourceData();
            carrier.setId(CommonUtil.genMongoId(riskOrderInfo.getString("orderId"), riskOrderInfo.getInteger("userId")));
            carrier.setOrderId(riskOrderInfo.getString("orderId"));
            carrier.setUserId(riskOrderInfo.getInteger("userId"));
            carrier.setTimestamp(System.currentTimeMillis());
            carrier.setData(carrierData);
            sourceDataMongoDao.saveSourceData(carrier, collectionName);
            log.info("【{}】运营商数据获取 collection - 【{}】, _id - 【{}】 - 成功"
                    , riskOrderInfo.getString("orderId"), collectionName, carrier.getId());
        } else {
            log.info("【{}】运营商数据获取 - 失败", riskOrderInfo.getString("orderId"));
        }
    }
}
